package com.springboot.dubbo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.dubbo.config.ReferenceConfig;
import com.springboot.common.util.StringUtil;
import com.springboot.config.ConsumerConfig;
import com.springboot.dubbo.cluster.CustomCluster;
import com.springboot.dubbo.service.UserService;

/**
 * 用户dubbo消费者配置
 *
 * @author supu
 * @create 2019-01-04 18:23
 **/
@Configuration
public class UserDubboConsumerConfig {
    private static final String TIMEOUT = "5000";

    @Autowired
    private DubboConfigFactory dubboConfigFactory;
    @Autowired
    private ConsumerConfig consumerConfig;

    @Bean
    public UserService userService() {
        return getServiceConfig(UserService.class);
    }

    private <T> T getServiceConfig(Class<T> tClass){
        ReferenceConfig<T> configReference = new ReferenceConfig<>();
        configReference.setInterface(tClass);
        configReference.setGroup(consumerConfig.getString(ConsumerConfig.DUBBO_GROUP));
        configReference.setApplication(dubboConfigFactory.consumerApplicationConfig());
        configReference.setRegistry(dubboConfigFactory.registryConfig());
        configReference.setCheck(Boolean.parseBoolean(consumerConfig.getString(ConsumerConfig.DUBBO_DEPENDENCY_CHECK)));
        String timeout = StringUtil.isEmpty(consumerConfig.getString(ConsumerConfig.DUBBO_TIMEOUT)) ? TIMEOUT : consumerConfig.getString(ConsumerConfig.DUBBO_TIMEOUT);
        configReference.setTimeout(Integer.parseInt(timeout));
        configReference.setCluster(CustomCluster.NAME);
        return configReference.get();
    }
}
